package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.constant.SensorConstants;
import edu.ynu.se.xiecheng.achitectureclass.dto.ApiResponse;
import edu.ynu.se.xiecheng.achitectureclass.dto.SensorDataResponse;
import edu.ynu.se.xiecheng.achitectureclass.entity.SensorData;
import edu.ynu.se.xiecheng.achitectureclass.service.SensorDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "传感器数据接口")
@RestController
@RequestMapping("/api/sensor")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = {"Authorization", "Content-Type"}, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
@Slf4j
public class SensorDataController {
    
    private final SensorDataService sensorDataService;
    
    @ApiOperation("获取传感器数据")
    @GetMapping("/data")
    @ResponseBody
    public ResponseEntity<?> getSensorData() {
        try {
            log.info("开始获取传感器数据");
            List<SensorDataResponse> data = sensorDataService.getGreenhouseSensorData();
            log.info("成功获取传感器数据: {}", data);
            return ResponseEntity.ok(new ApiResponse<>(200, "success", data));
        } catch (Exception e) {
            log.error("获取传感器数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ApiResponse<>(500, e.getMessage(), null));
        }
    }
    
    @ApiOperation("获取指定时间点的传感器数据")
    @GetMapping("/history/point")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getHistoricalDataByTime(
            @RequestParam(value = "timestamp", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime timestamp) {
        log.info("获取指定时间点的传感器数据: {}", timestamp);
        try {
            Map<String, Object> response = new HashMap<>();
            List<Map<String, Object>> data = sensorDataService.getDataByTime(timestamp);
            log.info("成功获取指定时间点的传感器数据: {}", data);
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取指定时间点的传感器数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    @ApiOperation("获取时间范围内的传感器数据")
    @GetMapping("/history/range")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getAllHistoricalData(
            @RequestParam(value = "startTime", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(value = "endTime", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        log.info("获取时间范围内的传感器数据: startTime={}, endTime={}", startTime, endTime);
        try {
            Map<String, Object> response = new HashMap<>();
            List<Map<String, Object>> data = sensorDataService.getAllDataByTimeRange(startTime, endTime);
            log.info("成功获取时间范围内的传感器数据: count={}", data.size());
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取时间范围内的传感器数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
